#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest
import os
import subprocess

import wc
class Test_wc_count(unittest.TestCase):
    def __init__(self, test_name):

        def test_func():
            file_handle = open('testcases/%s'%(test_name), "r");
            nline, nword, nchar, nbyte, maxlinelen = list(wc.count(file_handle))
            file_handle.seek(0)
            correct = subprocess.check_output(["wc", '-l', '-w', '-m', '-c', '-L'],
                                              stdin = file_handle);
            self.assertRegexpMatches(correct,
                                     "%d\\s+%d\\s+%d\\s+%d\\s+%d"
                                     %(nline,nword,nchar,nbyte,maxlinelen))
            file_handle.close()

        setattr(self, test_name, test_func)
        super(Test_wc_count, self).__init__(test_name);

    def setUp(self):
        pass


class Test_wc_arg(unittest.TestCase):
    def gen_args(self):
        import random
        random.seed()
        arg_list = ['-c', '-m', '-l', '-L', '-w']
        narg = random.randint(0, len(arg_list))
        return random.sample(arg_list, narg)

    def cleanup(self, s):
        return s.strip().split()

    def __init__(self, test_name):

        def test_func():
            import subprocess
            file_handle = open('testcases/%s'%(test_name), "r");

            for time in xrange(10):
                args = self.gen_args()
                file_handle.seek(0)
                result = subprocess.check_output(['./wc.py'] + args,
                                                 stdin = file_handle)
                result = self.cleanup(result)
                file_handle.seek(0)
                correct = subprocess.check_output(["wc"] + args,
                                                  stdin = file_handle);
                correct = self.cleanup(correct)
                self.assertEqual(result, correct)

            file_handle.close()

        setattr(self, test_name, test_func)
        super(Test_wc_arg, self).__init__(test_name);

    def setUp(self):
        pass

if __name__ == '__main__':
    testcases = [Test_wc_count(f) for f in os.listdir('testcases')]
    suite = unittest.TestSuite(testcases)
    testcases = [Test_wc_arg(f) for f in os.listdir('testcases')]
    suite.addTests(testcases)
    unittest.TextTestRunner(verbosity=3).run(suite)
